package cn.crawler.app.crown.commons.websocket.action;

import cn.crawler.app.crown.commons.websocket.filter.EncryptFilter;
import cn.crawler.app.crown.commons.websocket.main.action.BaseNettyAction;
import cn.crawler.app.crown.commons.websocket.main.action.NettyAction;
import cn.crawler.app.crown.commons.websocket.main.base.NettyRouter;
import cn.crawler.app.crown.commons.websocket.main.base.TextWebSocketFrameHandler;
import cn.crawler.app.crown.modules.models.CrownConfig;
import cn.crawler.app.crown.modules.models.CrownMatch;
import cn.crawler.app.crown.modules.services.CrownConfigService;
import cn.crawler.app.crown.modules.services.CrownMatchService;
import cn.crawler.app.crown.modules.services.result.MatchResultService;
import cn.crawler.framework.util.JSONUtil;
import cn.crawler.framework.util.Result;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.apache.commons.collections.CollectionUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.List;

@IocBean
@NettyAction(uri = "/crown/match/result", filters = {EncryptFilter.class})
public class ResultAction extends BaseNettyAction {

    private static final Log log = Logs.get();

    @Inject
    private CrownConfigService configService;
    @Inject
    private CrownMatchService matchService;
    @Inject
    private MatchResultService resultService;


    @Override
    public Result action(Channel income, JSONObject params) {
        log.info("action /crown/match/result income" + income + "params" + params);
        List<String> mids = JSONUtil.parseStringToJavaList(String.class, params.get("mids").toString());
        if (CollectionUtils.isNotEmpty(mids)) {
            // 获取爬虫账号
            CrownConfig crownConfig = configService.syncOne("手动获取赛果任务");
            if (crownConfig != null) {
                List<CrownMatch> list = matchService.query(Cnd.where("mid", "in", mids));
                list.forEach(match -> resultService.crawler(match, crownConfig));
                return Result.success();
            } else {
                return Result.error();
            }
        }
        return Result.error();
    }

    /**
     * 总球数数据列表订阅
     * 分页推送
     *
     * @return
     */
    @Override
    public Result subscribe(NettyRouter router) {
        log.info("subscribe /crown/match/result:" + router);
        if (TextWebSocketFrameHandler.checkSubscribed(router)) {
            return Result.error().addMsg("you have subscribed the key already.");
        }
        return Result.success();
    }

    public static BaseNettyAction instance() {
        return BaseNettyAction.instance(ResultAction.class);
    }
}
